﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Dao
{
    public class UserInRoles_Dao
    {
        /// <summary>
        /// 新增一条记录
        /// </summary>
        /// <param name="entity">记录实体</param>
        /// <returns>操作影响的行数</returns>
        public int Add( string userId, string roleId)
        {
            using (var context = new Dao.ErpEntities())
            {
                Guid uid = Guid.Parse(userId);
                Guid rid = Guid.Parse(roleId);
                User user = context.UserSet.FirstOrDefault(c => c.Id == uid);
                Role role = context.RoleSet.FirstOrDefault(c => c.Id == rid);
                
                user.Roles.Add(role);
                return context.SaveChanges();
            }
        }

        /// <summary>
        /// 删除一条记录
        /// </summary>
        /// <param name="id">记录Id</param>
        /// <returns>操作影响的行数</returns>
        public int Delete(string userId, string roleId)
        {
            using (var context = new Dao.ErpEntities())
            {
                Guid uid = Guid.Parse(userId);
                Guid rid = Guid.Parse(roleId);
                User user = context.UserSet.FirstOrDefault(c => c.Id == uid);
                Role role = context.RoleSet.FirstOrDefault(c => c.Id == rid);

                if (user != null)
                {
                    user.Roles.Remove(role);
                    return context.SaveChanges();
                }
                return 0;
            }
        }

        public List<string> GetByUser(string userId)
        {
            List<string> list = new List<string>();
            using (var context = new Dao.ErpEntities())
            {
                Guid uid = Guid.Parse(userId);
                User user = context.UserSet.FirstOrDefault(c => c.Id == uid);
                foreach (var c in user.Roles)
                {
                    list.Add(c.Id.ToString());
                }
                return list;
            }
        }
    }
}
